package com.iweibo.util;

import com.iweibo.bean.UserInfo;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SharedPreferencesTools {
	// 文件名
	private static final String FILE_NAME = "user_info";

	/**
	 * 保存数据
	 * 
	 * @param context
	 *            程序上下文对象
	 * @param info
	 *            用户信息
	 * @return true:成功<br>
	 *         false:失败
	 */
	public static boolean saveData(Context context, UserInfo info) {
		if (null == info) {
			return false;
		}
		SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
				Context.MODE_PRIVATE);
		Editor editor = sp.edit();
		editor.putLong("userId", info.getUserId());
		editor.putString("userName", info.getUserName());
		editor.putString("token", info.getToken());
		editor.putInt("expiresIn", info.getExpiresIn());
		editor.commit();
		return true;
	}

	/**
	 * 获取用户数据
	 * 
	 * @param context
	 *            程序上下文对象
	 * @return
	 */
	public static UserInfo getUserData(Context context) {
		SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
				Context.MODE_PRIVATE);
		long userId = sp.getLong("userId", 0);
		String userName = sp.getString("userName", null);
		String token = sp.getString("token", null);
		int expiresIn = sp.getInt("expiresIn", -1);
		if (0 == userId) {
			return null;
		} else {
			return new UserInfo(userId, userName, token, -1, expiresIn, 0);
		}

	}
}
